package cn.enjoy.tool.juc;

import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author K
 * @date 2021/7/29 下午2:03
 */
public class WaitNotify {
    private static boolean flag = true;
    private static final Object lock = new Object();

    public static void main(String[] args) throws Exception {
        Thread waitThread = new Thread(new Wait(), "WaitThread");
        waitThread.start();
        TimeUnit.SECONDS.sleep(1);
        Thread notifyThread = new Thread(new Notify(), "NotifyThread");
        notifyThread.start();
        System.out.println();
    }

    static class Wait implements Runnable {
        @Override
        public void run() {
            // 加锁，拥有lock的Monitor
            synchronized (lock) {
                // 当条件满足时，打印日志。然后lock.wait(); 释放lock对象的锁，等待其它线程的唤醒
                // 当条件不满足时，程序结束，释放lock对象的锁
                while (flag) {
                    try {
                        System.out.println(Thread.currentThread() + " flag is true. wait" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //再次获取到锁后，打印日志
                    System.out.println(Thread.currentThread() + " flag is false. running" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                }
            }
        }
    }

    static class Notify implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            // 加锁，拥有lock的Monitor
            synchronized (lock) {
                // 获取lock的对象锁，然后进行通知，通知时不会释放锁。直到当前线程释放了lock后，waitThread才能从wait方法中返回，并被唤醒
                System.out.println(Thread.currentThread() + " hold lock. notify" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notifyAll();
                flag = false;
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //再次加锁
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock again. sleep" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}